package com.itheima.d4_algorithm;

/**
 * 目标：掌握二分查找算法。
 *
 * binarySearch
 */
public class Test3 {
    public static void main(String[] args) {
        int[] arr={12,24,36,48,68,75,98,158};
        int num=68;
        int index = searchNum(arr, num);
        System.out.println(index);
    }
    public static int searchNum(int[] arr, int num){
        //定义两个变量存储做标
        int left=0;
        int right=arr.length-1;
        //2找到中间数
        while(left <= right){
            //每次循环，都从中间数开始比较，如果中间数大于num，则向左边找，如果中间数小于num，则向右边找
            int mid = (left+right)/2;
            if(arr[mid]>num){
                right=mid-1;
            }else if(arr[mid]<num){
                left=mid+1;
            }else{
                //返回下标
                return mid;
            }
        }
        return -1;
    }
}
